import React, {Component} from 'react';
import {connect} from 'react-redux';

import PropTypes from 'prop-types';

import {Row, Col, Select, Form, Input, Button, Radio, Icon, Modal, DatePicker} from 'antd';


import PageLayout from '../../layout/PageLayout';
import UserTable from '../../components/UserTable';

import {
    searchUserList,
    createUser,
} from '../../store/actions/userAction';

import styles from './UserManager.module.less';

const {Item} = Form;
const FormItem = Form.Item;
const {Option} = Select;

const RadioGroup = Radio.Group;

//子组件,有自定义方法method
class SearchForm extends React.Component {


    handleReset = () => {
        this.props.form.resetFields();
    };

    handleSubmit = (e) => {
        e.preventDefault();
    };


    render() {
        const {getFieldDecorator} = this.props.form;
        const {handleSearch} = this.props;

        return (
            <div>
                <Form
                    onSubmit={this.handleSubmit}
                    className={styles.form}
                >
                    <Row gutter={24}>
                        <Col span={8}>
                            <FormItem
                                label="用户账号"
                                className={styles.item}
                            >
                                {getFieldDecorator(`account`)(
                                    <Input type="text" placeholder="请输入用户账号..."/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="用户名称"
                                className={styles.item}
                            >
                                {getFieldDecorator(`name`)(
                                    <Input type="text" placeholder="请输入用户名称..."/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="用户邮箱"
                                className={styles.item}
                            >
                                {getFieldDecorator(`email`)(
                                    <Input type="text" placeholder="请输入用户邮箱..."/>
                                )}
                            </FormItem>
                        </Col>
                    </Row>

                    <Row gutter={24}>
                        <Col span={20}>
                            <FormItem
                                className={styles.buttonItem}
                            >
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    onClick={handleSearch}
                                >搜索</Button>
                                <Button
                                    type="reset"
                                    onClick={this.handleReset}
                                    style={{marginLeft: 8}}
                                >重置</Button>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            </div>
        );
    }
}

const WrappedSearchFormWithRef = Form.create()(SearchForm);

//子组件,有自定义方法method
class CreateForm extends React.Component {

    constructor(props){
        super(props);
        this.state={
            confirmDirty: false,
        }
    }

    handleReset = () => {
        this.props.form.resetFields();
    };

    handleSubmit = (e) => {
        e.preventDefault();
    };
    handleConfirmBlur = (e) => {
        const value = e.target.value;
        this.setState({confirmDirty: this.state.confirmDirty || !!value});
    };
    checkConfirm =(rule, value, callback) =>{

        const form = this.props.form;
        if (value && this.state.confirmDirty) {
            form.validateFields(['confirm'], { force: true });
        }
        callback();
    };
    checkPassword =(rule, value, callback) =>{

        const form = this.props.form;
        if (value && value !== form.getFieldValue('password')) {
            callback('您输入的两次密码不一致!');
        } else {
            callback();
        }
    };


    render() {
        const {getFieldDecorator} = this.props.form;
        const {handleSearch} = this.props;

        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 15},
        };

        return (
            <div>
                <Form
                    layout="horizontal"
                    onSubmit={this.handleSubmit}
                >
                    <FormItem
                        {...formItemLayout}
                        label="账号"
                        className={styles.item}
                    >
                        {getFieldDecorator(`account`, {
                            rules: [{
                                pattern: /^[0-9a-zA-Z_-]{6,20}/, message: '账号由6-20位数字字母-_组成！',
                            }, {
                                required: true, message: '请输入账号！',
                            }],
                        })(
                            <Input type="text" placeholder="请输入账号..."/>
                        )}
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="邮箱"
                        className={styles.item}
                    >
                        {getFieldDecorator(`email`, {
                            rules: [{
                                type: "email"
                            }, {
                                required: true, message: '邮箱不能为空!',
                            }]
                        })(
                            <Input type="text" placeholder="请输入邮箱..."/>
                        )}
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="密码"
                        className={styles.item}
                    >
                        {getFieldDecorator(`password`, {
                            rules: [{
                                pattern: /^[0-9a-zA-Z_-]{8,20}/, message: '密码由8-20位数字字母-_组成！',
                            }, {
                                required: true, message: '密码不能为空!',
                            }, {
                                validator: this.checkConfirm,
                            }]
                        })(
                            <Input type="password" placeholder="请输入密码..."/>
                        )}
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="确认密码"
                        className={styles.item}
                    >
                        {getFieldDecorator(`confirm`, {
                            rules: [{
                                required: true, message: '请确认密码...',
                            },{
                                validator: this.checkPassword,
                            }]
                        })(
                            <Input
                                type="password"
                                placeholder="请确认密码..."
                                onBlur={this.handleConfirmBlur}
                            />
                        )}
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="用户名"
                        className={styles.item}
                    >
                        {getFieldDecorator(`name`, {
                            rules: [{
                                max: 80, message: '用户名最大长度为80！'
                            }],
                        })(
                            <Input type="text" placeholder="请输入用户名..."/>
                        )}
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="手机号码"
                        className={styles.item}
                    >
                        {getFieldDecorator(`mobile`, {
                            rules: []
                        })(
                            <Input type="text" placeholder="请输入手机号..."/>
                        )}
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="生日"
                        className={styles.item}
                    >
                        {getFieldDecorator(`birthday`, {
                            rules: []
                        })(
                            <DatePicker format="YYYY-MM-DD"/>
                        )}
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="性别"
                        className={styles.item}
                    >
                        {getFieldDecorator(`sex`, {
                            rules: [],
                            initialValue: "0",
                        })(
                            <Radio.Group>
                                <Radio.Button value="0">男</Radio.Button>
                                <Radio.Button value="1">女</Radio.Button>
                            </Radio.Group>
                        )}
                    </FormItem>

                </Form>
            </div>
        );
    }
}

const WrappedCreateFormWithRef = Form.create()(CreateForm);


class UserManager extends Component {

    constructor(props) {
        super(props);
        this.state = {
            visible: false,
        }
    }


    componentDidMount() {

        this.props.searchUserList();
    }

    handleSearch = () => {

        this.props.searchUserList(this.searchForm.props.form.getFieldsValue());
    };

    handlePageChange = (pageNum, pageSize) => {

        const queryData = this.searchForm.props.form.getFieldsValue();

        this.props.searchUserList({pageNum, pageSize, ...queryData});
    };

    handleModalVisible = (visible) => {

        this.setState({
            visible: !!visible,
        });
    };


    handleModalOk = () => {

        const form = this.createForm.props.form;

        console.log(form.getFieldsValue());

        form.validateFields((err, values) => {
            if (err) {
                return;
            }

            console.log('Received values of form: ', values);

            this.props.createUser(values);
        });

        // this.props.createUser();
    };


    render() {

        const {userList, userListPage} = this.props;
        const {loading, list} = userList;

        return (
            <PageLayout>
                <WrappedSearchFormWithRef
                    handleSearch={this.handleSearch}
                    wrappedComponentRef={(inst) => this.searchForm = inst}
                >
                </WrappedSearchFormWithRef>
                <div className={styles.tableListOperator}>
                    <Button
                        type="primary"
                        onClick={() => this.handleModalVisible(true)}
                        style={{marginLeft: 8}}
                    ><Icon type="plus"/>新增</Button>
                </div>
                <UserTable
                    loading={loading}
                    data={list}
                    pagination={userListPage}
                    handleSearch={this.handlePageChange}
                />
                <Modal
                    title="添加用户"
                    visible={this.state.visible}
                    onOk={this.handleModalOk}
                    onCancel={() => this.handleModalVisible(false)}
                >
                    <WrappedCreateFormWithRef
                        wrappedComponentRef={(inst) => this.createForm = inst}
                    >

                    </WrappedCreateFormWithRef>
                </Modal>
            </PageLayout>
        );
    }


}

function mapStateToProps(state, ownProps) {
    return {
        userList: state.userList,
        userListPage: state.userListPage,
    }
}

function mapDispatchToProps(dispatch, ownProps) {
    return {
        searchUserList: (...args) => dispatch(searchUserList(...args)),
        createUser: (...args) => dispatch(createUser(...args)),
    }
}


export default connect(mapStateToProps, mapDispatchToProps)(UserManager);
